Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

Faraz

By Faraz -

Learn how to create an interactive Number Guessing Game from scratch using HTML, CSS, and JavaScript with this beginner-friendly tutorial.


Build a Number Guessing Game using HTML, CSS, and JavaScript with Source Code.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Welcome to the exciting world of web development! In this tutorial, we'll embark on a journey to create a captivating Number Guessing Game using the trifecta of web technologies: HTML, CSS, and JavaScript.

Whether you're a complete beginner or a seasoned coder looking to expand your skills, building a Number Guessing Game is a fantastic way to dive into the fundamentals of web development. Throughout this tutorial, we'll provide step-by-step guidance, demystifying each aspect of the development process.

By the end of this tutorial, you'll have a fully functional game that you can share with friends, showcase in your portfolio, or even customize further to make it uniquely yours. So, let's roll up our sleeves and embark on this exciting coding adventure!

Source Code

Step 1 (HTML Code):

Setting up the HTML structure:

  • Create a new HTML file.
  • Define the necessary HTML elements such as buttons, input fields, and text displays.
  • Organize the elements to create a clear and intuitive game interface.

Here's a breakdown of the code:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used (HTML5 in this case).

2. <html lang="en">: This opening tag indicates the start of the HTML document and specifies the language of the document (English).

3. <head>: This section contains meta-information about the document, such as the character encoding, viewport settings, title, and links to external resources like stylesheets and scripts.

  • <meta charset="UTF-8">: Specifies the character encoding of the document to UTF-8, which includes most characters from the vast majority of written languages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Provides instructions to the browser on how to render the webpage for compatibility purposes.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport width to the device width and sets the initial zoom level to 1.0, ensuring the webpage is displayed properly on various devices.
  • <title>Number Guessing Game</title>: Sets the title of the webpage displayed in the browser's title bar or tab.
  • <link href="https://fonts.goo..." rel="stylesheet">: Links to an external stylesheet hosted on Google Fonts, importing the "Krona One" font to be used on the webpage.
  • <link rel="stylesheet" href="styles.css">: Links to an external stylesheet named "styles.css" located in the same directory as the HTML file.

4. <body onload="generate();">: This section contains the content of the webpage that will be displayed to the user. The onload attribute calls the JavaScript function generate() when the page finishes loading.

  • <h1>Guess The Number</h1>: Displays the main heading of the webpage.
  • <h2>Between 0 and 1000</h2>: Displays a secondary heading indicating the range of numbers for the guessing game.
  • <h5 id="nomoreattempts"></h5>: An empty heading element with an ID, used for displaying messages to the user.
  • <div id="resultarea">: Defines a division (or container) for the result area of the game.
  • <section id="result">: Defines a section for displaying the result of the user's guess.
  • <section id="result2">: Another section for displaying additional result information.
  • <h4 id="status"></h4>: An empty heading element with an ID, used for displaying the status of the game.
  • <section id="result3">: Third section for displaying game statistics.
  • <p id="stats">Game Stats:</p>: Displays a label for the game statistics.
  • <div id="attempt">: Displays the number of attempts made by the user.
  • <div id="guessessofar">: Displays the user's previous guesses.
  • <div id="score">: Displays the number of wins.
  • <div id="streak">: Displays the user's winning streak.
  • <div id="inputarea">: Defines a division for the input area of the game.
  • <input type="number" placeholder="Your Guess Here..." id="guess">: Provides an input field where users can enter their guesses, with a placeholder text.
  • <button onclick="check()" id="submit">Submit Guess</button>: A button triggering the check() function when clicked, validate the user's guess.
  • <button onclick="reveal()" id="giveup"> Give Up?</button>: A button triggering the reveal() function when clicked, reveals the correct answer to the user.
  • <button onclick="generate()" id="other"> Try Another Number</button>: A button triggering the generate() function when clicked, generate a new random number for the user to guess.

5. <script src="script.js"></script>: Links to an external JavaScript file named "script.js" located in the same directory as the HTML file, which contains the logic for the number guessing game.

Step 2 (CSS Code):

Styling the game interface with CSS:

  • Link the CSS file to the HTML document.
  • Apply styles to the HTML elements to improve aesthetics and user experience.
  • Consider using colors, fonts, and layout techniques to make the game visually appealing.

Let's break down the code:

1. Body Styles:

  • background-color: orange;: Sets the background color of the entire webpage to orange.

2. Header Styles (h1, h2, h4):

  • text-align: center;: Centers the text within the headers.
  • font-family: 'Krona One', sans-serif;: Specifies the font family for the headers, prioritizing 'Krona One' if available, otherwise using a generic sans-serif font.
  • color: navy;: Sets the text color to navy blue.
  • font-size: Sets the font size for different header levels.

3. Result Div (ID: result, result2, result3):

  • border: Sets a double navy blue border with a thickness of 5 pixels around the result divs.
  • border-radius: Rounds the corners of the result divs.
  • box-shadow: Adds a gray shadow with an offset of 10 pixels to the bottom right.
  • margin: Specifies the outer margin of the result divs.
  • min-height, min-width, max-height, max-width: Sets the minimum and maximum dimensions for the result divs.
  • background-color: Sets the background color of the result divs to gold.
  • background-size: cover;: Scales the background image to cover the entire area of the result divs.

4. Button and Input Styles:

  • background-color, color: Sets the background color and text color of buttons to gold and navy respectively.
  • font-weight: Sets the font weight of buttons to bold.
  • width, height: Sets the width and height of buttons and inputs.
  • border: Specifies the border properties for buttons and inputs.
  • border-radius: Rounds the corners of buttons and inputs.
  • margin: Sets the outer margin of inputs.
  • ::placeholder: Specifies the styles for placeholder text in inputs.

5. Container Styles (ID: resultarea, inputarea):

  • display: flex;: Turns the containers into flex containers.
  • flex-flow: Specifies the direction of flex items and wrapping behavior.
  • justify-content: Aligns flex items along the main axis.

6. Span and Other Styles:

  • align-self: Aligns the other element within its flex container.
  • padding: Specifies the padding of the submit button.
  • margin-left: Sets the left margin of the give-up button.

7. Hover Styles:

  • button:hover: Specifies styles for buttons when hovered, such as adding a gray shadow.

8. Additional Styles (ID: attempt, h5, score, streak, guessessofar, stats, guesscounter, currentguess):

  • These styles define various aspects of text elements, including font size, color, padding, and background color.
body {
  background-color: orange;
}
h1 {
  text-align: center;
  font-family: 'Krona One', sans-serif;
  color: navy;
  font-size: 300%;
}
h2 {
  text-align: center;
  font-family: 'Krona One', sans-serif;
  color: navy;
  font-size: 150%;
  margin-top: -20px;
}
h4 {
  padding: 5px;
  font-family: 'Krona One', sans-serif;
  color: navy;
  font-size: 130%;
  text-align: center;
}
#result {
  border: 5px double navy;
  border-radius: 20px;
  box-shadow: gray 10px 10px;
  margin-bottom: 20px;
  min-height: 300px;
  max-height: 310px;
  min-width: 300px;
  max-width: 300px;
  background-color: gold;
  background-size: cover;
}
#result2 {
  min-height: 300px;
  background-color: gold;
  max-height: 310px;
  min-width: 155px;
  max-width: 180px;
  border: 5px double navy;
  border-radius: 20px;
  box-shadow: gray 10px 10px;
  margin-bottom: 20px;
  margin-left: 10px;
  display: flex;
  flex-flow: column;
  justify-content: center;
  padding: 5px;
}
#result3 {
  min-height: 300px;
  background-color: gold;
  max-height: 310px;
  min-width: 100px;
  max-width: 160px;
  border: 5px double navy;
  border-radius: 20px;
  box-shadow: gray 10px 10px;
  margin-bottom: 20px;
  margin-left: 10px;
  display: flex;
  flex-flow: column;
  justify-content: center;
  padding: 5px;
}
button {
  background-color: gold;
  color: navy;
  font-weight: bold;
  width: 150px;
  border-radius: 20px;
  height: 50px;
  border: none;
}
input {
  color: navy;
  font-weight: bold;
  width: 200px;
  height: 50px;
  border: none;
  margin-left: 0px;
  margin-right: 10px;
  border-radius: 10px;
}

#resultarea {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}
#inputarea {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}
span {
  font-family: 'Krona One', sans-serif;
  color: navy;
}
#other {
  background-color: gold;
  align-self: center;
  width: 200px;
}
#submit {
  padding: 50x;
  background-color: gold;
}
#giveup {
  background-color: gold;
  margin-left: 10px;
}
::placeholder {
  color: navy;
  opacity: 0.7;
}
button:hover {
  box-shadow: gray 5px 5px;
}
#attempt {
  font-family: sans;
  padding: 5px;
  font-weight: bold;
  color: navy;
  font-size: 15px;
  background-color: orange;
  margin-bottom: 10px;
}
h5 {
  color: navy;
  font-size: 30px;
  text-align: center;
  padding: 5px;
  font-weight: bold;
  margin-top: -10px;
  font-family: sans;
}
#score {
  font-family: sans;
  padding: 5px;
  font-weight: bold;
  color: navy;
  font-size: 15px;
  background-color: orange;
  margin-top: 10px;
  margin-bottom: 10px;
}
#streak {
  font-family: sans;
  padding: 5px;
  font-weight: bold;
  color: navy;
  font-size: 15px;
  background-color: orange;
  margin-bottom: 10px;
}
#guessessofar {
  font-family: sans;
  padding: 5px;
  font-weight: bold;
  color: navy;
  font-size: 15px;
  background-color: orange;
}
#stats {
  text-align: center;
  font-weight: bold;
  color: navy;
  font-family: 'Krona One', sans-serif;
  font-size: 130%;
}
#guesscounter {
  font-size: 14px;
}

#currentguess {
  color: navy;
  font-family: sans;
  font-weight: bold;
  margin: 7px;
  background-color: white;
  padding: 10px;
} 

Step 3 (JavaScript Code):

Adding interactivity with JavaScript:

  • Embed JavaScript code within the HTML document or link an external script file.
  • Write functions to handle game logic, such as generating a random number and comparing guesses.
  • Update the DOM dynamically to reflect game state changes and user interactions.

Let's break down the code into sections:

1. Variable Declarations:

  • result1, result2, result3: HTML elements with IDs result, result2, and result3.
  • guesscounter: HTML element with ID guesscounter.
  • streakcounter: HTML element with ID streakcounter.
  • scorecounter: HTML element with ID scorecounter.
  • resultimage: HTML element with ID result.
  • input: HTML input element with ID guess.
  • Initial values for streak and score are set to 0.
  • The inner HTML of streakcounter and scorecounter elements are set to display the current streak and score respectively.

2. Event Listener:

  • An event listener is added to the input element for the 'keyup' event. When the user presses the Enter key (event.keyCode === 13), it prevents the default action (form submission) and triggers a click on the submit button (document.getElementById('submit').click()).

3. Function Definitions:

  • generate(): This function generates a random number between 0 and 1000, sets the initial attempts to 0, and initializes various elements to start a new game.
  • check(): This function checks the user's guess against the randomly generated number. It handles scenarios where the guess is too low, too high, or correct. It also updates the UI accordingly.
  • reveal(): This function reveals the correct number when the player gives up. It also handles scenarios where the player didn't make any attempt or made only partial attempts.
var result1 = document.querySelector('#result');
var result2 = document.querySelector('#result2');
var result3 = document.querySelector('#result3');
var guesscounter = document.querySelector('#guesscounter');
var streakcounter = document.querySelector('#streakcounter');
var streak = 0;
streakcounter.innerHTML = ' ' + streak;
var scorecounter = document.querySelector('#scorecounter');
var score = 0;
scorecounter.innerHTML = ' ' + score;
var resultimage = document.querySelector('#result');
var input = document.getElementById('guess');

input.addEventListener('keyup', function (event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById('submit').click();
  }
});

function generate() {
  computerchoice = Math.floor(Math.random() * 1000 + 0);
  attempts = 0;
  attemptalert = document.querySelector('#nomoreattempts');
  attemptalert.style.display = 'block';
  numberofattempts = document.querySelector('#attemptcounter');
  numberofattempts.innerHTML = ' ' + attempts + '/15';
  h4 = document.querySelector('#status');
  h4.innerHTML = 'Try To Guess The Whole Number Between 0 And 1000.';
  h4.style.fontSize = '21px';
  var guesscounter = document.querySelector('#guesscounter');
  guesscounter.innerHTML = ' ';
  var newgamebutton = document.querySelector('#other');
  newgamebutton.style.display = 'none';
  var inputarea = document.querySelector('#guess');
  inputarea.style.display = 'inline';
  var submitbutton = document.querySelector('#submit');
  submitbutton.style.display = 'inline';
  var giveupbutton = document.querySelector('#giveup');
  giveupbutton.style.display = 'inline';
  attemptalert = document.querySelector('#nomoreattempts');
  attemptalert.innerHTML = 'You Have A Maximum Of 15 Attempts ';
  attemptalert.style.backgroundColor = 'orange';
  attemptalert.style.color = 'navy';
  var statusimage = document.querySelector('#result');
  statusimage.style.backgroundImage =
    "url('https://cdn.pixabay.com/photo/2016/05/28/05/40/question-mark-1421017_960_720.png')";
  result1.style.marginTop = '-10px';
  result2.style.marginTop = '-10px';
  result3.style.marginTop = '-10px';
}
function check() {
  var guess = document.querySelector('#guess').value;
  if (attempts > 13 && guess !== computerchoice) {
    streak = 0;
    streakcounter.innerHTML = ' ' + streak;
    attemptalert = document.querySelector('#nomoreattempts');
    attemptalert.innerHTML =
      'You Ran Out Of Attempts. The Number Was ' +
      computerchoice +
      '. Try Another Number.';
    attemptalert.style.backgroundColor = 'red';
    attemptalert.style.color = 'white';
    var newgamebutton = document.querySelector('#other');
    newgamebutton.style.display = 'block';
    var inputarea = document.querySelector('#guess');
    inputarea.style.display = 'none';
    var submitbutton = document.querySelector('#submit');
    submitbutton.style.display = 'none';
    var giveupbutton = document.querySelector('#giveup');
    giveupbutton.style.display = 'none';
  }
  if (guess == '') {
    h4.innerHTML = 'Type A Guess In The Box Below';
  } else {
    if (computerchoice == guess) {
      attemptalert.style.display = 'none';
      result1.style.marginTop = '75px';
      result2.style.marginTop = '75px';
      result3.style.marginTop = '75px';
      h4.innerHTML =
        'Well Done. You Correctly Guessed That The Number Was ' +
        computerchoice +
        '. Try Another Number.';
      document.querySelector('#scorecounter');
      var guesscounter = document.querySelector('#guesscounter');
      guesscounter.innerHTML += ' ' + guess;
      score++;
      streak++;
      scorecounter.innerHTML = ' ' + score;
      streakcounter.innerHTML = ' ' + streak;
      var inputarea = document.querySelector('#guess');
      inputarea.style.display = 'none';
      var statusimage = document.querySelector('#result');
      statusimage.style.backgroundImage =
        "url('https://www.publicdomainpictures.net/pictures/80000/velka/winners-trophy-clip-art.jpg')";
      var submitbutton = document.querySelector('#submit');
      submitbutton.style.display = 'none';
      var giveupbutton = document.querySelector('#giveup');
      giveupbutton.style.display = 'none';
      var newgamebutton = document.querySelector('#other');
      newgamebutton.style.display = 'block';
    } else if (guess < computerchoice && guess >= 0) {
      h4.innerHTML = 'Too Low...Guess Higher';
      attempts += 1;
      numberofattempts.innerHTML = ' ' + attempts + '/15';
      var statusimage = document.querySelector('#result');
      statusimage.style.backgroundImage =
        "url('https://cdn.pixabay.com/photo/2020/04/12/19/05/yellow-5035413_960_720.png')";
      var guesscounter = document.querySelector('#guesscounter');
      guesscounter.innerHTML += ' ' + guess + ',';
    } else if (guess > computerchoice && guess <= 1000) {
      h4.innerHTML = 'Too High...Guess Lower!';
      attempts += 1;
      numberofattempts.innerHTML = ' ' + attempts + '/15';
      var statusimage = document.querySelector('#result');
      statusimage.style.backgroundImage =
        "url('https://cdn.pixabay.com/photo/2019/05/27/23/45/plane-4234024_960_720.png')";
      var guesscounter = document.querySelector('#guesscounter');
      guesscounter.innerHTML += ' ' + guess + ',';
    }
  }
}
function reveal() {
  if (attempts == 0) {
    streak = 0;
    streakcounter.innerHTML = ' ' + streak;
    h4.innerHTML =
      'Did You Give Up? You Did Not Make Any Attempt To Guess The Number. Anyway, The Number Was ' +
      computerchoice +
      '. Try Another Number.';
    attemptalert.style.display = 'none';
    result1.style.marginTop = '75px';
    result2.style.marginTop = '75px';
    result3.style.marginTop = '75px';
    h4.style.fontSize = '16px';
    var statusimage = document.querySelector('#result');
    statusimage.style.backgroundImage =
      "url('https://cdn.pixabay.com/photo/2017/08/15/12/58/emoticon-2643814_960_720.jpg')";
    var newgamebutton = document.querySelector('#other');
    newgamebutton.style.display = 'block';
    var inputarea = document.querySelector('#guess');
    inputarea.style.display = 'none';
    var submitbutton = document.querySelector('#submit');
    submitbutton.style.display = 'none';
    var giveupbutton = document.querySelector('#giveup');
    giveupbutton.style.display = 'none';
  } else if (attempts > 0) {
    h4.innerHTML =
      'Did You Give Up? You Onlu Used ' +
      attempts +
      ' Of Your Attempts. Anyway, The Number Was ' +
      computerchoice +
      ' Try Another Number.';
    h4.style.fontSize = '16px';
    attemptalert.style.display = 'none';
    result1.style.marginTop = '75px';
    result2.style.marginTop = '75px';
    result3.style.marginTop = '75px';
    var statusimage = document.querySelector('#result');
    statusimage.style.backgroundImage =
      "url('https://cdn.pixabay.com/photo/2017/08/15/12/58/emoticon-2643814_960_720.jpg')";
    var newgamebutton = document.querySelector('#other');
    newgamebutton.style.display = 'block';
    var inputarea = document.querySelector('#guess');
    inputarea.style.display = 'none';
    var submitbutton = document.querySelector('#submit');
    submitbutton.style.display = 'none';
    var giveupbutton = document.querySelector('#giveup');
    giveupbutton.style.display = 'none';
  }
}

Final Output:

Build a Number Guessing Game using HTML, CSS, and JavaScript with Source Code.gif

Conclusion:

Congratulations on completing your journey in creating a dynamic Number Guessing Game using HTML, CSS, and JavaScript! You've taken a significant step forward in your web development journey, mastering key concepts and techniques along the way.

Thank you for joining us on this coding adventure. We wish you the best of luck in all your future endeavors in web development and beyond. Happy coding!

Code by: MoHus1

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺